import axios from 'axios'

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api',
  timeout: 30000, // 增加超时时间到30秒
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 统一错误处理
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 处理未授权错误
          console.error('未授权访问')
          break
        case 403:
          console.error('禁止访问')
          break
        case 404:
          console.error('请求资源不存在')
          break
        case 500:
          console.error('服务器错误')
          break
        default:
          console.error('请求失败')
      }
    }
    return Promise.reject(error)
  }
)

// 单词相关API
export const wordAPI = {
  // 获取单词列表
  getWords: (params = {}) => apiClient.get('/words/getAllWords', { params }),
  
  // 获取单个单词
  getWord: (id) => apiClient.get(`/words/${id}`),
  
  // 创建单词
  createWord: (wordData) => apiClient.post('/words', wordData),
  
  // 更新单词
  updateWord: (id, wordData) => apiClient.put(`/words/${id}`, wordData),
  
  // 删除单词
  deleteWord: (id) => apiClient.delete(`/words/${id}`),
  
  // 搜索单词
  searchWords: (keyword) => apiClient.get(`/words/search`, { params: { keyword } })
}

// 单词集相关API
export const wordSetAPI = {
  // 获取单词集列表
  getWordSets: (params = {}) => apiClient.get('/word-sets', { params }),
  
  // 获取单个单词集
  getWordSet: (id) => apiClient.get(`/word-sets/${id}`),
  
  // 创建单词集
  createWordSet: (wordSetData) => apiClient.post('/word-sets', wordSetData),
  
  // 更新单词集
  updateWordSet: (id, wordSetData) => apiClient.put(`/word-sets/${id}`, wordSetData),
  
  // 删除单词集
  deleteWordSet: (id) => apiClient.delete(`/word-sets/${id}`),
  
  // 向单词集添加单词
  addWordToSet: (setId, wordId) => apiClient.post(`/word-sets/${setId}/words`, { wordId }),
  
  // 从单词集移除单词
  removeWordFromSet: (setId, wordId) => apiClient.delete(`/word-sets/${setId}/words/${wordId}`),
  
  // 获取单词集内的单词
  getWordsInSet: (setId, params = {}) => apiClient.get(`/word-sets/${setId}/words`, { params })
}

// 学习计划相关API
export const studyPlanAPI = {
  // 获取学习计划列表
  getStudyPlans: (params = {}) => apiClient.get('/study-plans', { params }),
  
  // 获取单个学习计划
  getStudyPlan: (id) => apiClient.get(`/study-plans/${id}`),
  
  // 创建学习计划
  createStudyPlan: (planData) => apiClient.post('/study-plans', planData),
  
  // 更新学习计划
  updateStudyPlan: (id, planData) => apiClient.put(`/study-plans/${id}`, planData),
  
  // 删除学习计划
  deleteStudyPlan: (id) => apiClient.delete(`/study-plans/${id}`),
  
  // 完成每日任务
  completeDailyTask: (planId) => apiClient.post(`/study-plans/${planId}/complete`),
  
  // 更改计划状态
  changePlanStatus: (planId, status) => apiClient.patch(`/study-plans/${planId}/status`, { status })
}

// 语音设置相关API
export const voiceSettingAPI = {
  // 获取语音设置
  getVoiceSettings: (params = {}) => apiClient.get('/voice-settings', { params }),
  
  // 获取单个语音设置
  getVoiceSetting: (id) => apiClient.get(`/voice-settings/${id}`),
  
  // 创建语音设置
  createVoiceSetting: (settingData) => apiClient.post('/voice-settings', settingData),
  
  // 更新语音设置
  updateVoiceSetting: (id, settingData) => apiClient.put(`/voice-settings/${id}`, settingData),
  
  // 删除语音设置
  deleteVoiceSetting: (id) => apiClient.delete(`/voice-settings/${id}`),
  
  // 获取默认语音设置
  getDefaultVoiceSetting: () => apiClient.get('/voice-settings/default')
}

// 文本转语音相关API
export const textToSpeechAPI = {
  // 合成文本
  synthesizeText: (text, params = {}) => apiClient.post('/tts/synthesize', { text, ...params }),
  
  // 合成单词
  synthesizeWord: (word, params = {}) => apiClient.post('/tts/synthesize/word', { word, ...params }),
  
  // 合成单词集
  synthesizeWordSet: (wordSetId, params = {}) => apiClient.post(`/tts/synthesize/word-set/${wordSetId}`, params),
  
  // 获取音频资源
  getAudioResource: (audioId) => apiClient.get(`/tts/audio/${audioId}`, { responseType: 'blob' }),
  
  // 获取可用语音
  getAvailableVoices: () => apiClient.get('/tts/voices'),
  
  // 清除缓存
  clearCache: () => apiClient.post('/tts/cache/clear')
}

// 进度相关API
export const progressAPI = {
  // 获取学习进度
  getLearningProgress: () => apiClient.get('/progress'),
  
  // 更新学习进度
  updateLearningProgress: (progressData) => apiClient.post('/progress/update', progressData),
  
  // 获取学习统计
  getLearningStats: (params = {}) => apiClient.get('/progress/stats', { params })
}

// 导出所有API
export default {
  wordAPI,
  wordSetAPI,
  studyPlanAPI,
  voiceSettingAPI,
  textToSpeechAPI,
  progressAPI
}